package com.xfp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xfp.mapper.CategoryMapper;
import com.xfp.method.pageTotal;
import com.xfp.pojo.dto.CategoryDto;
import com.xfp.pojo.dto.CategoryQueryDto;
import com.xfp.pojo.entity.Category;
import com.xfp.pojo.vo.CategoryQueryVo;
import com.xfp.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImp implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增分类接口实现
     * @param categoryDto
     * @return
     */
    @Override
    public Boolean insert(CategoryDto categoryDto) throws Exception {
        //先查询是否存在有改分类
        Category exist = categoryMapper.findByName(categoryDto.getClassName());
        if(exist!=null){
            throw new Exception("该分类已存在");
        }
        System.out.println(categoryDto);
        //插入新分类
        int n = categoryMapper.insert(categoryDto);
        boolean b = true;
        if(n==0)
            b = false;
        return b;
    }

    /**
     * 分类分页查询实现
     * @param categoryQueryDto
     * @return
     */
    @Override
    public CategoryQueryVo pageQuery(CategoryQueryDto categoryQueryDto) {
        //启用pageHelper插件
        PageHelper.startPage(categoryQueryDto.getPageIndex(),categoryQueryDto.getPageSize());
        List<Category> categoriesList = categoryMapper.pageQuery(categoryQueryDto);
        Page page = (Page) categoriesList;
        //向下转型调用特有方法
        Long l = pageTotal.total(page.getTotal(),categoryQueryDto.getPageSize());
        CategoryQueryVo categoryQueryVo = new CategoryQueryVo();
        categoryQueryVo.setPageSize(categoryQueryDto.getPageSize());
        categoryQueryVo.setPageIndex(categoryQueryDto.getPageIndex());
        categoryQueryVo.setTotalPage(l);
        categoryQueryVo.setTotalCount(page.getTotal());
        categoryQueryVo.setCurrentPageRecords(page.getResult());
        System.out.println(categoryQueryVo);
        return categoryQueryVo;
    }

    /**
     * 获取分类基本信息
     * @param classId
     * @return
     */
    @Override
    public Category findById(Integer classId) throws Exception {
        Category category = categoryMapper.findById(classId);
        if (category==null){
            throw new Exception("该分类不存在");
        }
        return category;
    }

    /**
     * 根据id删除分类实现
     * @param classId
     */
    @Override
    public void deleteById(Integer classId) {
        categoryMapper.deleteById(classId);
    }

    /**
     * 更新分类
     * @param categoryDto
     * @return
     */
    @Override
    public Boolean update(Integer id,CategoryDto categoryDto) throws Exception {
        categoryDto.setClassId(id);
        int n = categoryMapper.update(categoryDto);
        return true;
    }
}
